<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import * as echarts from 'echarts';
import QuillEditor from './components/QuillEditor.vue';

// Chart reference and instance
const chartRef = ref<HTMLElement | null>(null);
let chartInstance: echarts.ECharts | null = null;

// 变量计数器，用于生成唯一ID
const variableCounter = ref(1);

// 函数：在编辑器内容的最后一个字符串之后插入红色变量
const insertVariableAtCursor = () => {
    try {
      // 获取Quill实例
      const quill = editorRef.value?.quillInstance;
      
      if (!quill) {
        alert('无法访问编辑器实例，请刷新页面重试');
        console.error('Quill instance is null despite editorReady being true');
        return;
      }
      
      // 获取编辑器内容的总长度（即内容末尾位置）
      // const contentLength = quill.getLength();
      // console.log('Inserting variable at content end, position:', contentLength - 1);
      
      // // 生成唯一的变量ID
      // const variableId = `var_${Date.now()}_${variableCounter.value++}`;
      // console.log('Generated variable ID:', variableId);
      
      // // 执行插入操作，在内容末尾添加红色变量
      // quill.clipboard.dangerouslyPasteHTML(Number(contentLength - 1), `<span class="variable-item" data-id="${variableId}" style="color: red">变量</span>`);
      
      // // 设置光标位置到变量后面
      // quill.setSelection(contentLength);
      // console.log('Variable inserted successfully, new cursor position:', contentLength);

      // 获取编辑器内容的长度
            const length = quill.getLength();
            
            // 设置光标到末尾
            quill.setSelection(length, 0);
            
            // 插入带样式的文本
            quill.insertText(length, 'buttonText', 'user');
            
            // 应用红色样式
            quill.formatText(length, 'buttonText'.length, {
              'color': '#e74c3c'
            }, 'user');
            
            // 将光标移动到插入内容之后
            quill.setSelection(length + 'buttonText'.length, 0, 'user');
    } catch (error) {
      console.error('Failed to insert variable:', error);
      alert('插入变量失败: ' + error.message);
    }
  };

// 异步获取柱状图配置
const getChartOptions = async (): Promise<echarts.EChartsOption> => {
  // 模拟异步获取过程，实际项目中可能是从API获取
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        animation: true,
        grid: { containLabel: true },
        xAxis: {
          type: 'category',
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: [120, 200, 150, 80, 70, 110, 130],
          type: 'bar',
          itemStyle: {
            color: '#409EFF'
          }
        }]
      });
    }, 300); // 模拟网络延迟
  });
};

// 异步获取折线图配置
const getLineChartOptions = async (): Promise<echarts.EChartsOption> => {
  // 模拟异步获取过程，实际项目中可能是从API获取
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        animation: true,
        grid: { containLabel: true },
        xAxis: {
          type: 'category',
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: [120, 200, 150, 80, 70, 110, 130],
          type: 'line',
          smooth: true,
          itemStyle: {
            color: '#67C23A'
          }
        }]
      });
    }, 300); // 模拟网络延迟
  });
};

// 存储当前的图表配置
let currentChartOptions: echarts.EChartsOption | null = null;

// 异步初始化图表
const initChart = async () => {
  if (chartRef.value) {
    // 异步获取图表配置
    currentChartOptions = await getChartOptions();
    
    chartInstance = echarts.init(chartRef.value);
    if (currentChartOptions !== null) {
      chartInstance.setOption(currentChartOptions);
    }
    
    // 添加双击事件监听器
    chartInstance.on('dblclick', () => {
      insertChartToEditor();
    });
    
    // 添加拖动事件监听器
    let isDragging = false;
    chartRef.value.addEventListener('mousedown', () => {
      isDragging = true;
    });
    
    chartRef.value.addEventListener('mouseup', () => {
      if (isDragging) {
        insertChartToEditor();
        isDragging = false;
      }
    });
  }
};

// 函数：将图表插入编辑器
const insertChartToEditor = async () => {
  debugger
  if (!chartInstance || !currentChartOptions) return;
  
  try {
    const quill = editorRef.value?.quillInstance;
    if (quill) {
      const range = quill.getSelection() || { index: 0 }; // quill.getSelection(true) 的参数 true 表示获取选中范围的索引，若不填则表示获取当前光标位置
      
      // 获取当前行信息
      const [line, offset] = quill.getLine(range.index);
      const lineLength = line.length();
      const endOfLineIndex = range.index - offset + lineLength;
      
      // 异步获取折线图配置
      const newChartOptions = await getLineChartOptions();
      
      // 在图表前后插入换行
      quill.insertText(endOfLineIndex, '\n');
      
      // 在下行插入图表
      quill.insertEmbed(endOfLineIndex + 1, 'chart', newChartOptions);
      
      // 在图表后再添加一个换行
      quill.insertText(endOfLineIndex + 2, '\n');
      
      // 将光标移到图表和换行后的位置
      quill.setSelection(endOfLineIndex + 3);
    }
  } catch (error) {
    console.error('Failed to insert chart:', error);
  }
};

// Editor reference
const editorRef = ref();
const editorReady = ref(false);

// 验证编辑器是否就绪
const checkEditorReady = () => {
  const isReady = !!editorRef.value?.quillInstance?.value;
  editorReady.value = isReady;
  console.log('Editor ready status:', isReady);
  return isReady;
};

// 组件挂载时检查编辑器状态
onMounted(() => {
  // 初始检查
  checkEditorReady();
  
  // 设置轮询检查，确保编辑器加载完成
  // const checkInterval = setInterval(() => {
  //   if (checkEditorReady()) {
  //     clearInterval(checkInterval);
  //     console.log('Editor is ready after polling');
  //   }
  // }, 300);

  // 组件卸载时清理
  // onUnmounted(() => clearInterval(checkInterval));
});

// 组件挂载时初始化
onMounted(async () => {
  await initChart();
  
  // 添加变量点击事件监听
  const editorContainer = document.querySelector('.ql-editor');
  if (editorContainer) {
    editorContainer.addEventListener('click', (e) => {
      const target = e.target as HTMLElement;
      if (target.classList.contains('variable-item')) {
        const variableId = target.getAttribute('data-id');
        if (variableId) {
          alert(`变量ID: ${variableId}`);
        }
      }
    });
  }
  
  // 处理窗口大小变化
  const handleResize = () => chartInstance?.resize();
  window.addEventListener('resize', handleResize);
  
  // 组件卸载时清理
  onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
    if (chartInstance) {
      chartInstance.dispose();
      chartInstance = null;
    }
  });
});
</script>

<template>
  <div class="app-container">
    <!-- Chart container -->
    <div class="chart-container">
      <div ref="chartRef" class="chart"></div>
      <div class="chart-instructions">双击或拖动图表以将其插入到编辑器中</div>
    </div>
    
    <!-- Editor container -->
    <div class="editor-container">
        <button class="add-variable-btn" @click="insertVariableAtCursor">添加变量</button>
        <QuillEditor ref="editorRef" />
      </div>
  </div>
</template>

<style scoped>
.app-container {
  display: flex;
  gap: 20px;
  padding: 20px;
  height: 100vh;
  background-color: #f5f7fa;
}

.chart-container {
  width: 600px;
  background: white;
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 16px;
}

.chart {
  width: 100%;
  height: 400px;
}

.chart-instructions {
  text-align: center;
  color: #606266;
  font-size: 14px;
  margin-top: 12px;
}

.editor-container {
  flex: 1;
  min-width: 0;
  background: white;
  border-radius: 8px;
  padding: 16px;
}

.add-variable-btn {
  margin-bottom: 16px;
  padding: 8px 16px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.add-variable-btn:hover {
  background-color: #66b1ff;
}

.variable-item {
  color: #409eff;
  cursor: pointer;
  text-decoration: underline;
  margin: 0 2px;
}

:deep(.rich-text-editor) {
  height: 100%;
}
</style>
